﻿namespace PlaylistCopy.Logging
{
    using Autofac;
    using Autofac.Core;
    using PlaylistCopy.Contract;
    using System;
    using System.Linq;

    public class LoggingModule : Module
    {

        protected override void Load(ContainerBuilder builder)
        {
            builder.Register((ctx, type) => GetLogger(type.TypedAs<Type>()));

            base.Load(builder);
        }

        protected override void AttachToComponentRegistration(
                    IComponentRegistry registry, IComponentRegistration registration)
        {
            registration.Preparing +=
                (sender, args) =>
                {
                    var forType = args.Component.Activator.LimitType;

                    var logParameter = new ResolvedParameter(
                        (p, c) => p.ParameterType == typeof(ILogger),
                        (p, c) => c.Resolve<ILogger>(TypedParameter.From(forType)));

                    args.Parameters = args.Parameters.Union(new[] { logParameter });
                };
        }

        private static ILogger GetLogger(Type type)
        {
            return new PlaylistCopyLogger(type.Name);
        }
    }
}